const yargs = require('yargs');
const env = yargs.argv['env'];
const config = env == 'development' ? require('./config.js').dev : require('./config.js').prod;
const shell = require('shelljs');
const path = require('path');
let Client = require('ssh2-sftp-client');
require('events').EventEmitter.defaultMaxListeners = 0

// 打包 npm run build
const compileDist = async () => {
  if (env == 'development') {
    if(shell.exec(`npm run build:preview`).code == 0) {
      console.log("测试环境 打包成功")
    }
  } else {
    if(shell.exec(`npm run build`).code == 0) {
      console.log("生产环境 打包成功")
    }
  }
}

const deleteFile = (filePath, sftp) => {
  return sftp.stat(filePath).then((data) => {
    if (data.isDirectory) {
      return sftp.rmdir(filePath, true)
    } else {
      return sftp.delete(filePath)
    }
  }).catch((err) => {
    console.log(err, '删除文件失败')
  })
}

async function connectSSh() {
  let sftp = new Client();
  sftp.connect({
    host: config.ip, // 服务器 IP
    port: config.port,
    username: config.username,
    password: config.password
  }).then(() => {
    // 获取远程dist文件夹下的文件
    return sftp.list(config.path)
  }).then((data) => {
    let promises = []
    for (let i = 0; i < data.length; i++) {
      let filePath = config.path + data[i]['name']
      promises.push(deleteFile(filePath, sftp))
    }
    Promise.all(promises).then(() =>{
      console.log('删除文件成功')
      return sftp.uploadDir(path.resolve(__dirname, '../dist'), config.path)
    }).then(() => {
      console.log('上传文件成功')
      sftp.end()
    }).catch((err) => {
      console.log(err, "失败")
      sftp.end()
    })
  })
}
async function runTask() {
  await compileDist()     //打包完成
  await connectSSh()      //提交上传
}
runTask()